1804E - Routing - CodeForces Solution


bitmasks dp graphs

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
typedef long long llint;

const int maxn = 30;
const int base = 31337;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
const int logo = 20;
const int off = 1 << logo;
const int treesiz = off << 1;

int n, m;
vector< int > graph[maxn];
bool good[treesiz];
int dp[maxn][treesiz];
int ans[maxn];

int f(int x, int mask, int mini) {
	int &ret = dp[x][mask];
	if (ret != -1) return ret;

	ret = -2;
	for (int tren : graph[x]) {
		if (tren < mini) continue;
		if (tren == mini) {
			if (good[mask]) ret = mini;
		}
		if (mask & (1 << tren)) continue;
		if (f(tren, mask | (1 << tren), mini) != -2) ret = tren;
	}
	return ret;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 0; i < m; i++) {
		int a, b;
		scanf("%d%d", &a, &b); a--, b--;

		graph[a].push_back(b);
		graph[b].push_back(a);
	}

	int lim = (1 << n);
	for (int mask = 0; mask < lim; mask++) {
		bool flag = true;
		for (int i = 0; i < n; i++) {
			if (mask & (1 << i)) continue;
			bool tflag = false;
			for (int tren : graph[i]) {
				if (mask & (1 << tren)) tflag = true;
			}
			if (!tflag) flag = false;
		}
		good[mask] = flag;
	}

	for (int i = 0; i < n; i++)
		for (int j = 0; j < lim; j++) dp[i][j] = -1;

	int sol = -2;
	for (int i = 0; i < n; i++) {
		if (f(i, 1 << i, i) != -2) sol = i;
	}

	if (sol == -2) printf("No\n");
	else {
		printf("Yes\n");
		int stat = sol;

		int cp = stat;
		int mask = 1 << sol;
		//printf("debug: %d\n", sol.X);
		while (true) {
			//printf("tren: %d %d\n", stat, mask);
			ans[stat] = dp[stat][mask];
			int nex = dp[stat][mask];
			if (nex == cp) break;
			//system("pause");

			stat = nex;
			mask |= (1 << nex);
		}

		for (int i = 0; i < n; i++) {
			if (mask & (1 << i)) continue;
			for (int tren : graph[i]) {
				if (mask & (1 << tren)) ans[i] = tren;
			}
		}

		for (int i = 0; i < n; i++) printf("%d ", ans[i] + 1);
		printf("\n");
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

1711A - Perfect Permutation
1701B - Permutation
1692A - Marathon
1066A - Vova and Train
169B - Replacing Digits
171D - Broken checker
380C - Sereja and Brackets
1281B - Azamon Web Services
1702A - Round Down the Price
1681C - Double Sort
12A - Super Agent
1709A - Three Doors
1680C - Binary String
1684B - Z mod X = C
1003A - Polycarp's Pockets
1691B - Shoe Shuffling
1706A - Another String Minimization Problem
1695B - Circle Game
1702B - Polycarp Writes a String from Memory
1701A - Grass Field
489C - Given Length and Sum of Digits
886B - Vlad and Cafes
915A - Garden
356A - Knight Tournament
1330A - Dreamoon and Ranking Collection
1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String